package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Database {
	private Connection conn = null;
	private static Database myDB;
	
	public static Database getInstance(){
		if(myDB == null)
			myDB = new Database();
		return myDB;
	}
	
	public Connection getConnection() throws SQLException {
			
				try {
					checkDriver();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					System.out.println(e.getMessage());
				}
				if (conn == null ) {
				conn = DriverManager.getConnection(util.Constants.dbUrl, 
						util.Constants.dbUserName,
						util.Constants.dbPassword);
				}
			return conn;
		
	}

	private void checkDriver() throws ClassNotFoundException {
		Class.forName(util.Constants.dbDriverPath);
	}

	private void closeConnection() throws SQLException {
			if (conn != null && !conn.isClosed())
				conn.isClosed();
	}

	private void rollBackConnection() throws SQLException {
			if (conn != null && conn.isClosed())
				conn.rollback();
		
	}
	
	public ResultSet executeQuery(PreparedStatement stmt) {
		ResultSet rs = null;
		try {
			getConnection();
			rs = stmt.executeQuery();
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			try {
				rollBackConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
			return null;
		}
		finally{
			try {
				closeConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return rs;
	}
	
	public int executeUpdate(PreparedStatement stmt)
	{
		int rowcount = 0;
		try {
			getConnection();
			rowcount = stmt.executeUpdate();
			
		}
		
		catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			try {
				rollBackConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}
			return 0;
		}
		finally{
			try {
				closeConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return rowcount;
	}

}
